#!/usr/bin/env sh

set -e
# set -x # debugger
set -u # no-unused-vars

function check_vars() {
  if [ "$1" == "major" ]; then
    return 0
  elif [ "$1" == "minor" ]; then
    return 0
  elif [ "$1" == "patch" ]; then
    return 0
  fi

  return 1
}

function main() {
  # 检查参数是否合法
  check_vars $@

  if [ "$?" == "1" ]; then
    echo "\033[31mthe only argument must be in \033[1m'major' or 'minor' or 'patch'\033[0m"
    exit 1
  fi

  # 更新版本并创建tag
  npm version $1

  if [ "$?" == "1" ]; then
    exit 1
  fi

  # 将更新后origin和tag一起push
  # git push --follow-tags

  PACKAGE_NAME=`cat package.json | head -2 | tail -1 | awk '{print $2}' | sed 's/["|,]//g'`
  VERSION=`cat package.json | head -3 | tail -1 | awk '{print $2}' | sed 's/["|,]//g'`

  TAR_FILE_NAME=${PACKAGE_NAME}-v${VERSION}.$1.tar.gz

  rm -rf ./dist ${PACKAGE_NAME}-v*.*.tar.gz
  npm run build
  tar -czf ${TAR_FILE_NAME} ./dist

  echo ${TAR_FILE_NAME} | pbcopy
}

main $@